package org.xmonkey.notifier.model;

import java.util.HashMap;

import org.eclipse.core.resources.IProject;
import org.eclipse.jdt.core.dom.ASTNode;
import org.xmonkey.Messages;
import org.xmonkey.util.Log;

/**
 * This class represents all the project subscriptions
 * @author jacopom
 *
 */
public class WorkspaceSubscriptions extends HashMap<IProject, ProjectNodeSubscriptions> {

	private static final long serialVersionUID = 6493660971159000177L;

	/**
	 * Subscribe the client for the specific node type in the specific project
	 * @param project the project
	 * @param nodeType the ASTNode type
	 * @param client the client that is subscribing
	 */
	public void subscribe(IProject project, int nodeType, ISubscriber client) {
		if(!this.containsKey(project)){
			this.put(project, new ProjectNodeSubscriptions(project));
		}
		
		ProjectNodeSubscriptions projectSubscription = this.get(project);
		
		if(!projectSubscription.containsKey(nodeType)){
			projectSubscription.put(nodeType, new OrderedSubscribersList());
		}
		
		// add the client to the ordered list of subscribers for the specific node of the specific project
		OrderedSubscribersList list = projectSubscription.get(nodeType);
		boolean addition = list.add(client);
		
		if (!addition){
			StringBuilder errorBuilder = new StringBuilder();
			errorBuilder.append(Messages.WorkspaceSubscriptions_0);
			errorBuilder.append(client.getSubscriberName());
			errorBuilder.append(Messages.WorkspaceSubscriptions_1);
			errorBuilder.append(project.getName());
			errorBuilder.append(Messages.WorkspaceSubscriptions_2);
			errorBuilder.append(ASTNode.nodeClassForType(nodeType));
			errorBuilder.append(Messages.WorkspaceSubscriptions_3);
			Log.printInfo(errorBuilder.toString(),  null);
		}
	}
	
	public String toString(){
		StringBuilder stringBuilder = new StringBuilder();
		
		stringBuilder.append(this.getClass().getCanonicalName());
		stringBuilder.append(Messages.WorkspaceSubscriptions_4);
		
		for (IProject project : this.keySet()){
			stringBuilder.append(Messages.WorkspaceSubscriptions_5);
			stringBuilder.append(project.getName());
			stringBuilder.append(Messages.WorkspaceSubscriptions_6);
			stringBuilder.append(this.get(project).toString());
		}
		
		return stringBuilder.toString();
	}

	/**
	 * Remove the subscriptions of the subscriber for the specific project
	 * @param project the project
	 * @param subscriber the subscriber to be removed for the specific project
	 */
	public void removeSubscriptions(IProject project, ISubscriber subscriber) {
		if (containsKey(project)){
			ProjectNodeSubscriptions projectSubscription = get(project);
			projectSubscription.removeSubscriptionsFor(subscriber);
		}
	}

}
